package edu.vt.ece_3574.amber_alert.location;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import edu.vt.ece_3574.amber_alert.AmberAlertApplication;
import edu.vt.ece_3574.amber_alert.accounts.Account;

public class C2DMRegistrationReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.w("C2DM", "Registration Receiver called");
		if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
			Log.w("C2DM", "Received registration ID");
			final String registrationId = intent.getStringExtra("registration_id");
			String error = intent.getStringExtra("error");

			Log.d("C2DM", "dmControl: registrationId = " + registrationId + ", error = " + error);

			SharedPreferences preferencesManager = context.getSharedPreferences(AmberAlertApplication.preferencesFileName, 0);
			SharedPreferences.Editor editor = preferencesManager.edit();
			editor.putString("c2dmRegistrationID", registrationId);
			editor.putBoolean("c2dmRegisteredAmberAlert", true);
			editor.commit();
			
			Account currentAccount = AmberAlertApplication.get().getCurrentAccount();
			if (currentAccount != null) {
				currentAccount.setSerialNumber(registrationId);
			}
		}
	}
}